package com.sysu.ooad.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.Action;
import com.sysu.ooad.entity.Course;
import com.sysu.ooad.entity.Group;
import com.sysu.ooad.entity.Student;
import com.sysu.ooad.service.CourseService;
import com.sysu.ooad.service.GroupService;

@Component
@Scope("prototype")
public class GroupManageStudentAction extends CommonAction {
	
	private CourseService courseService;
	private List<Group> groupList;
	private GroupService groupService;
	private String name;
	private Group group;
	private Group myGroup;
	
	public CourseService getCourseService() {
		return courseService;
	}
	@Resource
	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}
	public Group getMyGroup() {
		return myGroup;
	}
	public void setMyGroup(Group myGroup) {
		this.myGroup = myGroup;
	}
	
	public Group getGroup() {
		return group;
	}
	public void setGroup(Group group) {
		this.group = group;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public List<Group> getGroupList() {
		return groupList;
	}
	public void setGroupList(List<Group> groupList) {
		this.groupList = groupList;
	}
	public GroupService getGroupService() {
		return groupService;
	}
	
	@Resource
	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	public String studentIndex() throws Exception {
		Student s = this.findCurrentStudent();
		Group group = s.getGroup();
//		Course c = courseService.findById(s.getCourse().getId());
//		s.setCourse(c);
		if(group == null) {
			groupList = groupService.findByCourse(s.getCourse());
		} else {
			myGroup = groupService.getById(s.getGroup().getId());
		}
		return Action.SUCCESS;
	}
	
	public String createGroup() throws Exception {
		Student s = this.findCurrentStudent();
		groupService.create(s, name);
		return Action.SUCCESS;
	}
	
	public String joinGroup() throws Exception {
		Student s = this.findCurrentStudent();
		if(groupService.join(s, group)) {
			group = groupService.getById(group.getId());
			s.setGroup(group);
			return Action.SUCCESS;
		}
		else 
			return Action.ERROR;
	}
	
	public String leaveGroup() throws Exception {
		Student s = this.findCurrentStudent();
		if(s.isGroupLeader()) {
			groupService.dissolve(s.getGroup());
		}
		else {
			groupService.leave(s);
		}
		s.setGroup(null);
		return Action.SUCCESS;
	}
}
